<template>
  <div style="padding: 20px">
    <div class="headerBoxList">
      <svg width="24" height="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M12 13L34 34L23 44V4L34 14L12 35"
              stroke="#333"
              stroke-width="4"
              stroke-linecap="round"
              stroke-linejoin="round"/>
      </svg>
      <span style="margin-left: 10px">蓝牙信息</span>
    </div>
    <div class="contentBoxYY">
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item
          v-for="(item, index) in listData"
          :key="index"
          :title="'🚩 ' + item.titleKey + ` （${item.content.length}行）`"
          :name="index"
        >
          <div
            v-for="(data, j) in item.content"
            :key="j"
            style="background: #282828;color: rgb(101, 177, 235);padding-left:20px;"
          >
            {{ data }}
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script>
import { getRxTmpPathApi } from '@/api/phoneInfo/index'

export default {
  name: "Bluetooth",
  props: ['sendData'],
  data() {
    return {
      activeName: 0,
      listData: []
    };
  },
  watch: {
    '$store.state.account.basePhone': function () {
      this.initFunction();
    }
  },
  created() {
    this.initFunction();
  },
  methods: {
    initFunction() {
      let node = this.sendData;
      let dataJson = {
        proof_num: node.proof_num,
        rxTmpPath: node.href
      };

      getRxTmpPathApi(dataJson).then(res => {
        const stringData = res.data;
        const delimiters = [
          "Bluetooth Status",
          "Enable log",
          "BluetoothManagerService",
          "AdapterProperties",
          "AdapterState:",
          "btservice-BluetoothAdapterProperties",
          "btservice-BluetoothAdapterState:",
          "Metadata",
          "GATT Scanner Map",
          "com.gotokeep.keep",
          "android.uid.bluetooth:1002 (Registered)",
          "Device Volume Memory Map",
          "Bluetooth Config",
        ];

        const dataArray = [];

        for (let i = 0; i < delimiters.length; i++) {
          const delimiter = delimiters[i];
          const startIndex = stringData.indexOf(delimiter);
          const endIndex = i < delimiters.length - 1 ? stringData.indexOf(delimiters[i + 1]) : stringData.length;

          if (startIndex !== -1 && endIndex !== -1) {
            const data = stringData.slice(startIndex, endIndex).trim();
            dataArray.push(data);
          }
        }

        let arr = [];

        if (dataArray.length > 0) {
          // ✅ 正常使用关键词分段逻辑
          for (let index = 0; index < dataArray.length; index++) {
            const element = dataArray[index];
            const delimiterIndex = element.indexOf("\n");

            if (delimiterIndex !== -1) {
              const title = element.substring(0, delimiterIndex).trim();
              const content = element.substring(delimiterIndex + 1).trim().split("\n");
              arr.push({
                titleKey: title || "未知标题",
                content: content
              });
            } else {
              arr.push({
                titleKey: element.trim() || "未知标题",
                content: ["无详细内容"]
              });
            }
          }
        } else {
          // ❗️备用方案：缩进结构识别
          const lines = stringData.split('\n');
          let currentSection = null;

          lines.forEach(line => {
            const trimmed = line.trim();
            if (!trimmed) return;

            if (/^\S/.test(line)) {
              if (currentSection) arr.push(currentSection);
              currentSection = {
                titleKey: trimmed,
                content: []
              };
            } else if (/^\s+/.test(line)) {
              if (!currentSection) {
                currentSection = { titleKey: "未知标题", content: [] };
              }
              currentSection.content.push(trimmed);
            }
          });

          if (currentSection) arr.push(currentSection);

          if (!arr.length) {
            arr.push({
              titleKey: "蓝牙信息",
              content: ["未获取到任何蓝牙信息"]
            });
          }
        }

        this.listData = arr;
      }).catch(err => {
        console.error("蓝牙信息获取失败:", err);
        this.listData = [{
          titleKey: "蓝牙信息获取失败",
          content: ["接口异常或设备连接失败"]
        }];
      });
    }
  }
};
</script>

<style scoped>
.headerBoxList {
  width: 100%;
  height: 50px;
  border-bottom: 1px solid #d2d2d2;
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.contentBoxYY {
  width: 95%;
  margin: 0 auto;
  overflow: hidden;
  height: 86vh;
  overflow-y: auto;
  overflow-x: hidden;
  overflow-wrap: break-word;
}

@media screen and (min-width: 2360px) {
  .contentBoxYY {
    height: 81vh;
  }
}

@media screen and (min-width: 2561px) {
  .contentBoxYY {
    height: 67vh;
  }
}
</style>
